package cn.micai.base.concurrent;

/**
 * 描述：账户类
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/5/14 11:04
 */
public class Accout {

    private double balance;

    public Accout(double money) {
        this.balance = money;
        System.out.println("Totle Money: " + balance);
    }

    /**
     * 存款
     * @param money
     */
    public void deposit(double money) {
        balance = balance + money;
    }

    /**
     * 取款
     * @param money
     * @param delay
     */
    public synchronized void withdraw(double money, int delay) {
        if (balance >= money) {
            try {
                Thread.sleep(delay);
                balance = balance - money;
                System.out.println(Thread.currentThread().getName() + " withdraw " + money + " successful! " + balance);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println(Thread.currentThread().getName()+" balance is not enough, withdraw failed! " + balance);
        }
    }

    private static class AccountThread extends Thread {
        Accout accout;
        int delay;

        public AccountThread(Accout accout, int delay) {
            this.accout = accout;
            this.delay = delay;
        }

        @Override
        public void run() {
            accout.withdraw(100, delay);
        }
    }

    public static void main(String [] args) {
        Accout accout = new Accout(100);
        AccountThread at1 = new AccountThread(accout, 1000);
        AccountThread at2 = new AccountThread(accout, 0);
        at1.start();
        at2.start();
    }

}
